package com.tony.juc;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: ExchangerDemo001
 * @Auther: 皮蛋布丁
 * @Date: 2022/04/13/11:02
 * @Description: 生产者消费者
 */
public class ExchangerDemo001 {

    public static void main(String[] args) throws InterruptedException {

        int repeat = 20; // 定义生产和消费的次数
        Exchanger<String> exchanger = new Exchanger<>();
        new Thread(()->{
            for (int i = 0; i < repeat; i++) { //生产的次数
                String info = null; //保存最终的数据
                if (i % 2 == 0) {
                    info = "皮蛋布丁001";
                } else {
                    info = "皮蛋布丁002";
                }
                try {
                    TimeUnit.SECONDS.sleep(1); //模拟延迟
                    exchanger.exchange(info); //存储数据
                    System.out.printf("【%s】%s%n", Thread.currentThread().getName(), info);
                } catch (InterruptedException e) {e.printStackTrace();}
            }
        },"生产者").start();
        new Thread(()->{
            for (int i = 0; i < repeat; i++) {
                try {
                    TimeUnit.SECONDS.sleep(2); //模拟延迟
                    String info = exchanger.exchange(null); //数据获取
                    System.out.printf("〖%s〗%s%n",Thread.currentThread().getName(),info);
                } catch (InterruptedException e) {e.printStackTrace();}
            }
        },"消费者").start();
    }
}
